package cz.zcu.fav.rat.managed.bean;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import com.sun.faces.facelets.tag.composite.ImplementationHandler;

import cz.zcu.fav.rat.beans.User;
import cz.zcu.fav.rat.dataaccess.service.UserService;
import cz.zcu.fav.rat.managed.locale.LocaleMessageFactory;
import cz.zcu.fav.rat.security.beans.Role;
import cz.zcu.fav.rat.security.beans.UserSessionController;
import cz.zcu.fav.rat.security.service.RegisteredImplementors;

@ManagedBean
@ViewScoped
public class EditUserBean extends AbstractEditBean
{
	private static final long serialVersionUID = 1368369543965130997L;

	private User selectedUser;

	@PostConstruct
	public void init()
	{
		super.init();
		if (id != null)
		{
			selectedUser = getUserService().get(id);
		} else
		{
			selectedUser = new User();
			selectedUser.setImplementor(RegisteredImplementors.getImplementors().get(0));
		}
	}

	private UserService getUserService()
	{
		return SpringBeanFactory.getInstance().<UserService> getBean(
				"userService", UserService.class);
	}

	public void create()
	{
		getUserService().create(selectedUser);

		selectedUser = new User();
		selectedUser.setImplementor(RegisteredImplementors.getImplementors().get(0));
		String message = LocaleMessageFactory
				.getLocale("view.objectcreate.info.objectcreated");

		FacesContext.getCurrentInstance().addMessage("form",
				new FacesMessage(FacesMessage.SEVERITY_INFO, message, null));
	}

	public String edit()
	{
		getUserService().update(selectedUser);
		return "usertable?faces-redirect=true";
	}

	public User getSelectedUser()
	{
		return selectedUser;
	}

	public void setSelectedUser(User selectedUser)
	{
		this.selectedUser = selectedUser;
	}

	public Role[] getRoleValues()
	{
		return Role.values();
	}

	public String[] getImplementorValues()
	{
		List<String> implementors = RegisteredImplementors.getImplementors();
		return implementors.toArray(new String[implementors.size()]);
	}
	
	public boolean isPasswordStoredLocally()
	{
		return RegisteredImplementors.isPasswordStoredLocally(getSelectedUser().getImplementor());
	}
	

}
